{% extends "base.html" %}

{% block content %}
<div class="row">
    <div class="col-md-12">
        <h2>德育素质管理</h2>
        
        {% if current_user.role == 'student' %}
            <div class="card mt-4">
                <div class="card-header">
                    <h4>提交德育素质评分</h4>
                </div>
                <div class="card-body">
                    <form method="POST" action="{{ url_for('submit_moral') }}" enctype="multipart/form-data">
                        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                        
                        <div class="mb-3">
                            <label class="form-label">学期</label>
                            <select class="form-select" name="semester" required>
                                <option value="">请选择学期</option>
                                <option value="2023-2024">2023-2024</option>
                                <option value="2024-2025">2024-2025</option>
                            </select>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">基础分</label>
                            <input type="number" class="form-control" name="base_score" step="0.1" min="0" max="100" value="60" required>
                            <div class="form-text">默认基础分为60分，可根据实际情况调整（0-100分）</div>
                        </div>

                        <!-- 加分项容器 -->
                        <div class="mb-3">
                            <label class="form-label">加分项</label>
                            <div id="bonus-items">
                                <div class="row mb-2">
                                    <div class="col-md-6">
                                        <select class="form-select bonus-select" name="bonus_items[]" onchange="handleBonusSelect(this)">
                                            <option value="">请选择加分项</option>
                                            <option value="1">加分项1：担任学生干部</option>
                                            <option value="2">加分项2：参与志愿服务</option>
                                            <option value="3">加分项3：获得表彰奖励</option>
                                            <option value="4">加分项4：参与社会实践</option>
                                            <option value="5">加分项5：其他突出表现</option>
                                            <option value="other">其他</option>
                                        </select>
                                        <input type="text" class="form-control mt-2 other-input" name="bonus_other[]" style="display: none;" placeholder="请输入其他加分项内容">
                                    </div>
                                    <div class="col-md-4">
                                        <input type="number" class="form-control score-input" name="bonus_scores[]" step="0.1" min="0" max="100" placeholder="分数" required>
                                    </div>
                                    <div class="col-md-2">
                                        <button type="button" class="btn btn-danger btn-sm remove-item" onclick="removeItem(this)">删除</button>
                                    </div>
                                </div>
                            </div>
                            <button type="button" class="btn btn-secondary btn-sm mt-2" onclick="addBonusItem()" id="add-bonus-btn">
                                <i class="bi bi-plus"></i> 添加其他加分项
                            </button>
                        </div>

                        <!-- 减分项容器 -->
                        <div class="mb-3">
                            <label class="form-label">减分项</label>
                            <div id="penalty-items">
                                <div class="row mb-2">
                                    <div class="col-md-6">
                                        <select class="form-select penalty-select" name="penalty_items[]" onchange="handlePenaltySelect(this)">
                                            <option value="">请选择减分项</option>
                                            <option value="1">减分项1：违反校规校纪</option>
                                            <option value="2">减分项2：考勤异常</option>
                                            <option value="3">减分项3：宿舍卫生差</option>
                                            <option value="4">减分项4：不参与集体活动</option>
                                            <option value="5">减分项5：其他不良行为</option>
                                            <option value="other">其他</option>
                                        </select>
                                        <input type="text" class="form-control mt-2 other-input" name="penalty_other[]" style="display: none;" placeholder="请输入其他减分项内容">
                                    </div>
                                    <div class="col-md-4">
                                        <input type="number" class="form-control score-input" name="penalty_scores[]" step="0.1" min="0" max="100" placeholder="分数" required>
                                    </div>
                                    <div class="col-md-2">
                                        <button type="button" class="btn btn-danger btn-sm remove-item" onclick="removeItem(this)">删除</button>
                                    </div>
                                </div>
                            </div>
                            <button type="button" class="btn btn-secondary btn-sm mt-2" onclick="addBonusItem()" id="add-penalty-btn">
                                <i class="bi bi-plus"></i> 添加其他项
                            </button>
                        </div>

                        <!-- 证明材料上传 -->
                        <div class="mb-3">
                            <label class="form-label">证明材料（选填）</label>
                            <input type="file" class="form-control" name="proof_file" accept=".pdf,.jpg,.jpeg,.png">
                            <div class="form-text">支持PDF、JPG、PNG格式，大小不超过5MB</div>
                        </div>

                        <button type="submit" class="btn btn-primary">提交评分</button>
                    </form>
                </div>
            </div>

            <!-- 显示历史记录 -->
            <div class="card mt-4">
                <div class="card-header">
                    <h4>我的德育素质记录</h4>
                </div>
                <div class="card-body">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>学期</th>
                                <th>基础分</th>
                                <th>加分项</th>
                                <th>减分项</th>
                                <th>最终得分</th>
                                <th>状态</th>
                                <th>附件</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for record in moral_records %}
                            <tr>
                                <td>{{ record.semester }}</td>
                                <td>{{ record.base_score }}</td>
                                <td>
                                    {% for item in record.bonus_items %}
                                        {% if item.item == 'other' %}
                                            {{ item.other_content }}：+{{ item.score }}分<br>
                                        {% else %}
                                            {{ item.item }}：+{{ item.score }}分<br>
                                        {% endif %}
                                    {% endfor %}
                                </td>
                                <td>
                                    {% for item in record.penalty_items %}
                                        {% if item.item == 'other' %}
                                            {{ item.other_content }}：-{{ item.score }}分<br>
                                        {% else %}
                                            {{ item.item }}：-{{ item.score }}分<br>
                                        {% endif %}
                                    {% endfor %}
                                </td>
                                <td>{{ record.total_score }}</td>
                                <td>
                                    {% if record.status == 'pending' %}
                                        <span class="badge bg-warning">待审核</span>
                                    {% elif record.status == 'approved' %}
                                        <span class="badge bg-success">已通过</span>
                                    {% else %}
                                        <span class="badge bg-danger">已驳回</span>
                                    {% endif %}
                                </td>
                                <td>
                                    {% if record.proof_file %}
                                        <a href="{{ url_for('download_moral_proof', file_id=record.id) }}" class="btn btn-sm btn-secondary">
                                            查看附件
                                        </a>
                                    {% endif %}
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        {% else %}
            <!-- 教师查看界面 -->
            <div class="card mt-4">
                <div class="card-header">
                    <h4>待审核德育素质</h4>
                </div>
                <div class="card-body">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>学生</th>
                                <th>学期</th>
                                <th>基础分</th>
                                <th>加分项</th>
                                <th>减分项</th>
                                <th>总分</th>
                                <th>提交时间</th>
                                <th>状态</th>
                                <th>附件</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for record in moral_records %}
                            {% if record.status == 'pending' %}
                            <tr>
                                <td>{{ record.student.username }} - {{ record.student.real_name }}</td>
                                <td>{{ record.semester }}</td>
                                <td>{{ record.base_score }}</td>
                                <td>
                                    {% for item in record.bonus_items %}
                                        {% if item.item == 'other' %}
                                            {{ item.other_content }}：+{{ item.score }}分<br>
                                        {% else %}
                                            {{ item.item }}：+{{ item.score }}分<br>
                                        {% endif %}
                                    {% endfor %}
                                </td>
                                <td>
                                    {% for item in record.penalty_items %}
                                        {% if item.item == 'other' %}
                                            {{ item.other_content }}：-{{ item.score }}分<br>
                                        {% else %}
                                            {{ item.item }}：-{{ item.score }}分<br>
                                        {% endif %}
                                    {% endfor %}
                                </td>
                                <td>{{ record.total_score }}</td>
                                <td>{{ record.submit_time.strftime('%Y-%m-%d %H:%M') }}</td>
                                <td>
                                    <span class="badge bg-warning">待审核</span>
                                </td>
                                <td>
                                    {% if record.proof_file %}
                                        <a href="{{ url_for('download_moral_proof', file_id=record.id) }}" class="btn btn-sm btn-secondary">
                                            查看附件
                                        </a>
                                    {% endif %}
                                </td>
                                <td>
                                    <button type="button" class="btn btn-sm btn-success" onclick="approveScore('moral', {{ record.id }})">通过</button>
                                    <button type="button" class="btn btn-sm btn-danger" onclick="rejectScore('moral', {{ record.id }})">驳回</button>
                                </td>
                            </tr>
                            {% endif %}
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- 添加已审核成绩表格 -->
            <div class="card mt-4">
                <div class="card-header">
                    <h4>已审核德育素质</h4>
                </div>
                <div class="card-body">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>学生</th>
                                <th>学期</th>
                                <th>基础分</th>
                                <th>加分项</th>
                                <th>减分项</th>
                                <th>总分</th>
                                <th>提交时间</th>
                                <th>审核时间</th>
                                <th>状态</th>
                                <th>附件</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for record in moral_records %}
                            {% if record.status != 'pending' %}
                            <tr>
                                <td>{{ record.student.username }} - {{ record.student.real_name }}</td>
                                <td>{{ record.semester }}</td>
                                <td>{{ record.base_score }}</td>
                                <td>
                                    {% for item in record.bonus_items %}
                                        {% if item.item == 'other' %}
                                            {{ item.other_content }}：+{{ item.score }}分<br>
                                        {% else %}
                                            {{ item.item }}：+{{ item.score }}分<br>
                                        {% endif %}
                                    {% endfor %}
                                </td>
                                <td>
                                    {% for item in record.penalty_items %}
                                        {% if item.item == 'other' %}
                                            {{ item.other_content }}：-{{ item.score }}分<br>
                                        {% else %}
                                            {{ item.item }}：-{{ item.score }}分<br>
                                        {% endif %}
                                    {% endfor %}
                                </td>
                                <td>{{ record.total_score }}</td>
                                <td>{{ record.submit_time.strftime('%Y-%m-%d %H:%M') }}</td>
                                <td>{{ record.update_time.strftime('%Y-%m-%d %H:%M') if record.update_time else '' }}</td>
                                <td>
                                    {% if record.status == 'approved' %}
                                        <span class="badge bg-success">已通过</span>
                                    {% else %}
                                        <span class="badge bg-danger">已驳回</span>
                                    {% endif %}
                                </td>
                                <td>
                                    {% if record.proof_file %}
                                        <a href="{{ url_for('download_moral_proof', file_id=record.id) }}" class="btn btn-sm btn-secondary">
                                            查看附件
                                        </a>
                                    {% endif %}
                                </td>
                            </tr>
                            {% endif %}
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        {% endif %}
    </div>
</div>

{{ super() }}
<script>
let bonusCount = 1;
let penaltyCount = 1;

function handleBonusSelect(select) {
    const parentRow = select.closest('.row');
    const otherInput = parentRow.querySelector('.other-input');
    const scoreInput = parentRow.querySelector('.score-input');
    
    if (select.value === 'other') {
        otherInput.style.display = 'block';
        otherInput.required = true;
        scoreInput.style.display = 'block';
    } else {
        otherInput.style.display = 'none';
        otherInput.required = false;
        scoreInput.style.display = 'block';
    }
}

function handlePenaltySelect(select) {
    const parentRow = select.closest('.row');
    const otherInput = parentRow.querySelector('.other-input');
    const scoreInput = parentRow.querySelector('.score-input');
    
    if (select.value === 'other') {
        otherInput.style.display = 'block';
        otherInput.required = true;
        scoreInput.style.display = 'block';
    } else {
        otherInput.style.display = 'none';
        otherInput.required = false;
        scoreInput.style.display = 'block';
    }
}

function addBonusItem() {
    if (bonusCount >= 5) {
        alert('最多只能添加5个加分项');
        return;
    }
    
    const template = `
        <div class="row mb-2">
            <div class="col-md-6">
                <select class="form-select bonus-select" name="bonus_items[]" onchange="handleBonusSelect(this)">
                    <option value="">请选择加分项</option>
                    <option value="1">加分项1：担任学生干部</option>
                    <option value="2">加分项2：参与志愿服务</option>
                    <option value="3">加分项3：获得表彰奖励</option>
                    <option value="4">加分项4：参与社会实践</option>
                    <option value="5">加分项5：其他突出表现</option>
                    <option value="other">其他</option>
                </select>
                <input type="text" class="form-control mt-2 other-input" name="bonus_other[]" style="display: none;" placeholder="请输入其他加分项内容">
            </div>
            <div class="col-md-4">
                <input type="number" class="form-control score-input" name="bonus_scores[]" step="0.1" min="0" max="100" placeholder="分数" required>
            </div>
            <div class="col-md-2">
                <button type="button" class="btn btn-danger btn-sm remove-item" onclick="removeItem(this)">删除</button>
            </div>
        </div>
    `;
    
    document.getElementById('bonus-items').insertAdjacentHTML('beforeend', template);
    bonusCount++;
    
    if (bonusCount >= 5) {
        document.getElementById('add-bonus-btn').style.display = 'none';
    }
}

function addPenaltyItem() {
    if (penaltyCount >= 5) {
        alert('最多只能添加5个减分项');
        return;
    }
    
    const template = `
        <div class="row mb-2">
            <div class="col-md-6">
                <select class="form-select penalty-select" name="penalty_items[]" onchange="handlePenaltySelect(this)">
                    <option value="">请选择减分项</option>
                    <option value="1">减分项1：违反校规校纪</option>
                    <option value="2">减分项2：考勤异常</option>
                    <option value="3">减分项3：宿舍卫生差</option>
                    <option value="4">减分项4：不参与集体活动</option>
                    <option value="5">减分项5：其他不良行为</option>
                    <option value="other">其他</option>
                </select>
                <input type="text" class="form-control mt-2 other-input" name="penalty_other[]" style="display: none;" placeholder="请输入其他减分项内容">
            </div>
            <div class="col-md-4">
                <input type="number" class="form-control score-input" name="penalty_scores[]" step="0.1" min="0" max="100" placeholder="分数" required>
            </div>
            <div class="col-md-2">
                <button type="button" class="btn btn-danger btn-sm remove-item" onclick="removeItem(this)">删除</button>
            </div>
        </div>
    `;
    
    document.getElementById('penalty-items').insertAdjacentHTML('beforeend', template);
    penaltyCount++;
    
    if (penaltyCount >= 5) {
        document.getElementById('add-penalty-btn').style.display = 'none';
    }
}

function removeItem(button) {
    const parentRow = button.closest('.row');
    const isBonus = parentRow.closest('#bonus-items') !== null;
    
    parentRow.remove();
    
    if (isBonus) {
        bonusCount--;
        document.getElementById('add-bonus-btn').style.display = 'block';
    } else {
        penaltyCount--;
        document.getElementById('add-penalty-btn').style.display = 'block';
    }
}

function approveScore(type, recordId) {
    if (confirm('确定要通过这条成绩记录吗？')) {
        const token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
        
        fetch(`/approve_${type}/${recordId}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': token
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('审核通过成功！');
                window.location.reload();
            } else {
                alert('操作失败：' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('操作失败，请重试');
        });
    }
}

function rejectScore(type, recordId) {
    if (confirm('确定要驳回这条成绩记录吗？')) {
        const token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
        
        fetch(`/reject_${type}/${recordId}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': token
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('驳回成功！');
                window.location.reload();
            } else {
                alert('操作失败：' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('操作失败，请重试');
        });
    }
}
</script>
{% endblock %} 